import { createI18n, type LocaleMessages } from 'vue-i18n';

function loadLocaleMessages() {
  const messages = {} as LocaleMessages<{ 'en-US': { [index: string]: any } }>;
  const locales: Record<string, { default: any; [index: string]: any }> =
    import.meta.glob('./locales/*.json', {
      eager: true,
    });
  Object.keys(locales).forEach((key: string) => {
    const keyName = key.split('./locales/')[1].split('.json')[0];
    messages[keyName] = locales[key]!.default;
  });
  return messages;
}

export default createI18n({
  // Get default locale from local storage
  locale: window.localStorage.getItem('storedLanguage') as string | undefined,
  // Locales that don't exist will fallback to English
  fallbackLocale: 'en-US',
  allowComposition: true,
  // Falling back to fallbackLocale generates two console warnings
  // Silent fallback suppresses console warnings when using fallback
  silentFallbackWarn: true,
  messages: loadLocaleMessages(),
});
